﻿using JESAI.MonacoRoslynComplete.Builders;
using JESAI.MonacoRoslynComplete.Storage.MySql;
using JESAI.MonacoRoslynConplete.Storages;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ServiceBuildExtensions
    {
        public static IMonacoRoslynCompleteBuilder UseMySqlStorage(this IMonacoRoslynCompleteBuilder builder)
        {
            builder.Services.AddOptions();
            builder.Services.Configure<MySqlStorageOptions>(builder.Configuration.GetSection("Storage"));
            return builder.UseMySqlStorageService();
        }

        public static IMonacoRoslynCompleteBuilder UseMySqlStorage(this IMonacoRoslynCompleteBuilder builder, Action<MySqlStorageOptions> options)
        {
            builder.Services.AddOptions();
            builder.Services.Configure<MySqlStorageOptions>(options);

            return builder.UseMySqlStorageService();
        }

        internal static IMonacoRoslynCompleteBuilder UseMySqlStorageService(this IMonacoRoslynCompleteBuilder builder)
        {
            builder.Services.AddSingleton<IMonacoRoslynCompleteStorage, MySqlStorage>();
            builder.Services.AddSingleton<MySqlConnectionFactory>();

            return builder;

        }

        public static IMonacoRoslynCompleteBuilder InitStorage(this IMonacoRoslynCompleteBuilder builder)
        {
            var storage = builder.Services.BuildServiceProvider().GetService<IMonacoRoslynCompleteStorage>() ?? throw new ArgumentNullException("Storage Service Not Found");
            storage.CreateDatabaseAsync().Wait();
            storage.InitAsync().Wait();

            return builder;
        }
    }
}
